package com.mvd.app.commons;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.widget.Toast;

import com.mvd.app.api.ApiConfig;
import com.mvd.app.application.BaseApplication;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/6/23.
 */

public class ImageUtils implements ApiConfig{

    /**
     * 按尺寸压缩图片
     *
     * @param srcPath  图片路径
     * @param desWidth 压缩的图片宽度
     * @return Bitmap 对象
     */

    public static Bitmap compressImageFromFile(String srcPath, float desWidth) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;//只读边,不读内容
        Bitmap bitmap;
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        float desHeight = desWidth * h / w;
        int be = 1;
        if (w > h && w > desWidth) {
            be = (int) (newOpts.outWidth / desWidth);
        } else if (w < h && h > desHeight) {
            be = (int) (newOpts.outHeight / desHeight);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置采样率

//        newOpts.inPreferredConfig = Config.ARGB_8888;//该模式是默认的,可不设
        newOpts.inPurgeable = true;// 同时设置才会有效
        newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收

        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return bitmap;
    }

    /**
     * 压缩图片（质量压缩）
     *
     * @param image
     */

    public static File compressImage(Bitmap image, String path) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;

        while (baos.toByteArray().length / 1024 > 200) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            long length = baos.toByteArray().length;
        }
//        long length = baos.toByteArray().length;
//        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
//        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片


        File file = new File(path);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return file;
    }


    //从网上获取图片的流,然后保存的手机内存里面，并且在这里直接转为b64
    public static String doGetImagefileByByte(String url) {
        String result = null;
        Response response = null;
        try {
            OkHttpClient client = new OkHttpClient();//创建Http客户端。
            Request request;
            request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();//创造请求
            response = client.newCall(request).execute();//执行

            byte[] buff = response.body().bytes();


            /**
             *
             *使用流的方式保存到手机内存，
             * 内存地址是/storage/emulated/0/Android/data/com.example.yiqixue01/files/Pictures/
             * 文件名是hhh.jpeg
             */
            File file = new File(Environment.getExternalStorageDirectory(),external_path+ "/temp_my_app/" + System
                    .currentTimeMillis() + ".jpg");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            String outPath = Environment.getExternalStorageDirectory().getPath() + external_path+"/temp_my_app/" + System
                    .currentTimeMillis() + ".jpg";
            String pathLog = "doGetImagefileByByte()------photoPath----" + outPath;
            PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, pathLog.getBytes());
            FileOutputStream out = new FileOutputStream(outPath);
            out.write(buff);
            out.close();
            result = outPath;
            String pathLog2 = "doGetImagefileByByte()------result----" + result;
            PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, pathLog2.getBytes());
//            BASE64Decoder decoder = new BASE64Decoder();
//            byte[] imgbyte = decoder.decodeBuffer("刚刚将字节数组转成的字符串");
//            OutputStream os = new FileOutputStream("/Users/curry/text.png");
//            os.write(imgbyte, 0, imgbyte.length);
//            os.flush();
//            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static Bitmap getGossipImage(String gid, Context context) {
//        String httpUrl = httpDomain+"userpic/"+gid+".png";
        Bitmap bitmap = null;
        HttpGet httpRequest = new HttpGet(gid);
        //取得HttpClient 对象
        HttpClient httpclient = new DefaultHttpClient();
        try {
            //请求httpClient ，取得HttpRestponse
            HttpResponse httpResponse = httpclient.execute(httpRequest);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //取得相关信息 取得HttpEntiy
                HttpEntity httpEntity = httpResponse.getEntity();
                InputStream is = httpEntity.getContent();
                bitmap = BitmapFactory.decodeStream(is);
                is.close();
                String pathLog = "getGossipImage()------bitmap----" + bitmap;
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, pathLog.getBytes());
            } else {
                Toast.makeText(context, "连接失败!", Toast.LENGTH_SHORT).show();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}
